using System;
using System.Collections.Generic;
using System.Text;
using System.Data ;
using System.Data.SqlClient;
using System.Configuration;
using Entities;

namespace DAL
{
    public class tbDanhMucDAL
    {
        private SqlConnection cn = null;
        public tbDanhMucDAL()
        {
            cn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConnection"].ConnectionString);
            cn.Open();
        }

        public tbDanhMucDAL(tbDanhMucDAL tuan)
        {
            this.cn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConnection"].ConnectionString);
            this.cn.Open();
        }

        public void Insert(tbDanhMuc danhmuc)
        {
            SqlCommand cm = new SqlCommand("sp_tbDanhMuc_insert", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@TenDanhMuc", danhmuc.TenDanhMuc);
            cm.ExecuteNonQuery();
        }
        public void Update(tbDanhMuc danhmuc)
        {
            SqlCommand cm = new SqlCommand("sp_tbDanhMuc_update", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@MaDM", danhmuc.MaDM);
            cm.Parameters.AddWithValue("@TenDanhMuc", danhmuc.TenDanhMuc);
            cm.ExecuteNonQuery();
        }
        public void Delete(int iD)
        {
            SqlCommand cm = new SqlCommand("sp_tbDanhMuc_delete", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@MaDM", iD);
            cm.ExecuteNonQuery();
        }
        public tbDanhMucCollection Get(string where, int pageIndex, int pageSize,
            string orderBy, string orderDirection, out int totalRecords)
        {
            SqlCommand cm = new SqlCommand("sp_tbDanhMuc_get", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@Where", where);
            cm.Parameters.AddWithValue("@PageIndex", pageIndex);
            cm.Parameters.AddWithValue("@PageSize", pageSize);
            cm.Parameters.AddWithValue("@OrderBy", orderBy);
            cm.Parameters.AddWithValue("@OrderDirection", orderDirection);
            cm.Parameters.Add(new SqlParameter("@TotalRecords", DbType.Int32)).Direction = ParameterDirection.Output;

            SqlDataReader dr = cm.ExecuteReader();
            tbDanhMucCollection dmCollection = new tbDanhMucCollection();

            while (dr.Read())
            {
                tbDanhMuc danhmuc = new tbDanhMuc();
                danhmuc.MaDM = int.Parse(dr.GetValue(0).ToString());
                danhmuc.TenDanhMuc = dr.GetValue(1).ToString();
                dmCollection.Add(danhmuc);
            }
            dr.Close();
            totalRecords = int.Parse(cm.Parameters["@TotalRecords"].Value.ToString());
            return dmCollection;
        }
    }
}